package com.jackrain.nea.fc.cp.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jackrain.nea.common.PostHandleEvent;
import com.jackrain.nea.core.db.Tools;
import com.jackrain.nea.core.redis.RedisObjectSerializer;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.cp.api.ViewChrorgDeptSaveCmd;
import com.jackrain.nea.fc.cp.mapper.ViewChrorgMapper;
import com.jackrain.nea.fc.utils.ObjectToUtil;
import com.jackrain.nea.fc.utils.UserInformation;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.RuntimeCompute;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.query.DefaultWebEvent;
import com.jackrain.nea.web.query.QuerySessionImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;

/**
 * 组织信息-服务开发
 *
 * @author xuxinshuai
 * @create 2017/12/14
 */
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "cp")
public class ViewChrorgDeptSaveCmdImpl extends CommandAdapter implements ViewChrorgDeptSaveCmd {

    @Autowired
    PostHandleEvent postHandleEvent;

    @Override
    public ValueHolder execute(HashMap map) throws NDSException {


        ValueHolder vh = new ValueHolder();
        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(map.get("param"), "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
        log.info("ViewChrorgDeptSaveCmdImpl--param-->{}",param);

        if (null == param || param.size() == 0 || param.getJSONArray("data").size() <= 0) {
            throw new NDSException("参数格式错误！");
        }
//        log.debug("------------传入数据部门-----------");

        RuntimeCompute runtimeCompute = ApplicationContextHandle.getBean("runtimeCompute");
        runtimeCompute.startRuntime();
        ViewChrorgMapper viewChrorgMapper = ApplicationContextHandle.getBean(ViewChrorgMapper.class);
        JSONArray paramArray = param.getJSONArray("data");
        User user = Tools.getUser(UserInformation.USER_NAME);
        if (user == null) {
            throw new NDSException("USER不存在！");
        }
        //处理为空的数据
        JSONObject orgNullJo = handingOrgupIsNull(paramArray, viewChrorgMapper, user);
        //处理不为空的数据
        JSONObject orgNotNullJo = handingOrgupIsNotNull(paramArray, viewChrorgMapper, user);

        JSONArray errorArray = new JSONArray();
        JSONArray orgNullArray = orgNullJo.getJSONArray("errMessageArr");
        JSONArray orgNotNullArray = orgNotNullJo.getJSONArray("errMessageArr");
        if (orgNullArray != null && orgNullArray.size() > 0) {
            for (int i = 0; i < orgNullArray.size(); i++) {
                errorArray.add(orgNullArray.get(i));
            }
        }
        if (orgNotNullArray != null && orgNotNullArray.size() > 0) {
            for (int i = 0; i < orgNotNullArray.size(); i++) {
                errorArray.add(orgNotNullArray.get(i));
            }
        }
        JSONArray successIdsArray = new JSONArray();
        JSONArray orgNullIds = orgNullJo.getJSONArray("errIdArr");
        JSONArray orgNotNullIds = orgNotNullJo.getJSONArray("errIdArr");
        if (orgNullIds != null && orgNullIds.size() > 0) {
            for (int i = 0; i < orgNullIds.size(); i++) {
                successIdsArray.add(orgNullIds.get(i));
            }
        }
        if (orgNotNullIds != null && orgNotNullIds.size() > 0) {
            for (int i = 0; i < orgNotNullIds.size(); i++) {
                successIdsArray.add(orgNotNullIds.get(i));
            }
        }

        if (errorArray.size() > 0) {
            vh.put("error", errorArray);
            vh.put("successIds", successIdsArray);
            vh.put("code", -1);
        } else {
            vh.put("code", 0);
        }
        Double spendTime = runtimeCompute.endRuntime();
        vh.put("spendtime", spendTime);
        log.debug("---------组织部门执行时间--------->>" + spendTime);

        return vh;
    }

    //优先处理上级组织为空的数据
    public JSONObject handingOrgupIsNull(JSONArray paramArray, ViewChrorgMapper viewChrorgMapper, User user) {

        JSONObject errJo = new JSONObject();
        JSONArray errIdArray = new JSONArray();

        JSONArray errarray = new JSONArray();
        //处理pk_fatherorg为空的数据
        for (int i = 0; i < paramArray.size(); i++) {
            JSONObject paramObj = paramArray.getJSONObject(i);
            String hr002_id = paramObj.getString("HR002_ID");
            try {
                //上级部门为空
                String orgupid = paramObj.getString("pk_fatherorg");
                if (ObjectToUtil.isNullOREmpty(orgupid)) {
                    String deptlevel = paramObj.getString("deptlevel");
                    if ("6".equals(deptlevel)) {
                        //门店
                        // 判断FC中组织表中的数据是否存在HR001_ID=PK_org的数据
                        String pkorg = paramObj.getString("pk_org");
                        Integer orgCount = viewChrorgMapper.selectorgcount(pkorg);
                        if (orgCount <= 0) {
                            throw new NDSException(paramObj.getString("ECODE") + "部门的组织不存在，数据传输失败！");
                        }
                        //若存在，则取组织的ID，作为门店档案所属组织的ID
                        Long cphorgId = viewChrorgMapper.selectorgId(pkorg);
                        //判断FC店仓档案表中是否存在HR002_ID=PK_dept字段的数据
                        String olddept = paramObj.getString("old_dept");
                        String deptStr = null;
                        if (ObjectToUtil.isNullOREmpty(olddept)) {
                            //old_dept为空
                            deptStr = paramObj.getString("HR002_ID");
                        } else {
                            //old_dept不为空,查询old_dept是否存在于数据库中
                            Integer olddeptCount = viewChrorgMapper.selectStoreCount(olddept);
                            if (olddeptCount == 1) {
                                deptStr = olddept;
                            } else {
                                deptStr = paramObj.getString("HR002_ID");
//                                throw new NDSException("旧组织下门店档案不存在或存在多条数据，更新失败！");
                            }
                        }
                        Integer orgDeptCount = viewChrorgMapper.selectStoreCount(deptStr);
                        if (orgDeptCount > 0) {
                            //存在更新“编码”、“名称”、“HR组织”、“修改时间”字段的值
                            List<HashMap> storeidlist = viewChrorgMapper.selectStoreId(deptStr);
                            if (storeidlist.size() > 1) {
                                throw new NDSException("CP_C_STORE表HR002_ID条件存在多行记录：" + paramObj.getString("HR002_ID"));
                            }
                            HashMap storeMap = storeidlist.get(0);
                            Long storeid = (Long) storeMap.get("ID");

                            JSONObject updateObj = new JSONObject();
                            updateObj.put("ECODE", paramObj.getString("ECODE"));
                            updateObj.put("CP_C_HRORG_ID", cphorgId);
                            updateObj.put("ENAME", paramObj.getString("ENAME"));
                            updateObj.put("MODIFIEDDATE", paramObj.getString("MODIFIEDDATE"));
                            updateObj.put("HR002_ID", paramObj.getString("HR002_ID"));

                            if ("N".equals(paramObj.getString("ISACTIVE"))) {
                                updateObj.put("TXTDIM1", "Y");
                            } else if ("Y".equals(paramObj.getString("ISACTIVE"))) {
                                updateObj.put("TXTDIM1", "N");
                            }
                            if (!ObjectToUtil.isNullOREmpty(paramObj.getString("HR003_ID"))) {
                                Long bigId = viewChrorgMapper.selectEmpId(paramObj.getString("HR003_ID"));
                                updateObj.put("BIGMANAGER", bigId);
                            }else {

                                updateObj.put("BIGMANAGER", null);

                            }

                            //TODO 不调用标准服务
//                            updateObj.put("MODIFIERNAME", user.getName());
//                            updateObj.put("MODIFIERENAME", user.getEname());
//                            updateObj.put("MODIFIERID", Integer.valueOf(user.getId()).longValue());
//                            updateObj.put("ID", storeid);
//                            int updateRes=viewChrorgMapper.updateStore(updateObj);
//                            if (updateRes<=0){
//                                throw new NDSException("部门更新失败");
//                            }
                            //TODO 调标准服务
                            JSONObject jo = new JSONObject();
                            jo.put("objid", storeid);
                            jo.put("table", "CP_C_RSTORE");
                            JSONObject fixJo = new JSONObject();
                            fixJo.put("CP_C_RSTORE", updateObj);
                            jo.put("fixcolumn", fixJo);
                            QuerySessionImpl userquerySession = new QuerySessionImpl(user);
                            DefaultWebEvent event = new DefaultWebEvent("test", new HashMap());
                            event.put("param", jo);
                            userquerySession.setEvent(event);

                            JSONObject retJo = postHandleEvent.executePostHandle(jo, userquerySession, event, "save");
                            if (retJo.get("code") != null && (int) retJo.get("code") < 0) {
                                throw new NDSException("" + retJo.get("message") + retJo.get("error"));
                            }


                        } else {
                            //若不存在则新增一条门店档案的信息
                            JSONObject insertStore = new JSONObject();
                            insertStore.put("AD_CLIENT_ID", Integer.valueOf(user.getClientId()).longValue());
                            insertStore.put("AD_ORG_ID", Integer.valueOf(user.getOrgId()).longValue());
                            if ("N".equals(paramObj.getString("ISACTIVE"))) {
                                insertStore.put("TXTDIM1", "Y");
                            } else if ("Y".equals(paramObj.getString("ISACTIVE"))) {
                                insertStore.put("TXTDIM1", "N");
                            }
                            insertStore.put("HR002_ID", paramObj.getString("HR002_ID"));
                            insertStore.put("ECODE", paramObj.getString("ECODE"));
                            insertStore.put("ENAME", paramObj.getString("ENAME"));
                            insertStore.put("STORENATURE", "STO");
                            insertStore.put("CP_C_HRORG_ID", cphorgId);
                            insertStore.put("CREATIONDATE", paramObj.getString("MODIFIEDDATE"));
                            insertStore.put("MODIFIEDDATE", paramObj.getString("MODIFIEDDATE"));
                            if (!ObjectToUtil.isNullOREmpty(paramObj.getString("HR003_ID"))) {
                                Long bigId = viewChrorgMapper.selectEmpId(paramObj.getString("HR003_ID"));
                                insertStore.put("BIGMANAGER", bigId);
                            }else {

                                insertStore.put("BIGMANAGER", null);

                            }

                            //TODO 不调用标准服务
//                            insertStore.put("MODIFIERNAME", user.getName());
//                            insertStore.put("MODIFIERENAME", user.getEname());
//                            insertStore.put("MODIFIERID", Integer.valueOf(user.getId()).longValue());
//                            insertStore.put("OWNERID", Integer.valueOf(user.getId()).longValue());
//                            insertStore.put("OWNERNAME", user.getName());
//                            insertStore.put("OWNERENAME", user.getEname());
//                            Long storeId = Tools.getSequence("CP_C_STORE");
//                            insertStore.put("ID", storeId);
//                            int insertRes=viewChrorgMapper.insertRstore(insertStore);
//                            if (insertRes<=0){
//                                throw new NDSException("部门新增失败");
//                            }

                            //TODO 调标准服务
                            JSONObject jo = new JSONObject();
                            jo.put("objid", -1);
                            jo.put("table", "CP_C_RSTORE");
                            JSONObject fixJo = new JSONObject();
                            fixJo.put("CP_C_RSTORE", insertStore);
                            jo.put("fixcolumn", fixJo);

                            QuerySessionImpl userquerySession = new QuerySessionImpl(user);

                            DefaultWebEvent event = new DefaultWebEvent("test", new HashMap());
                            event.put("param", jo);

                            userquerySession.setEvent(event);


                            JSONObject retJo = postHandleEvent.executePostHandle(jo, userquerySession, event, "save");
                            if (retJo.get("code") != null && (int) retJo.get("code") < 0) {
                                throw new NDSException("" + retJo.get("message") + retJo.get("error"));
                            }


                        }

                    } else {
                        //非门店
                        String pkorg = paramObj.getString("pk_org");
                        if (ObjectToUtil.isNullOREmpty(pkorg)) {
                            throw new NDSException("所属组织不能为空！");
                        }
                        Integer hr001Count = viewChrorgMapper.selectorgcount(pkorg);
                        if (hr001Count <= 0) {
                            throw new NDSException(paramObj.getString("ECODE") + "部门的所属组织不存在，数据传输失败！");
                        }
                        Long cphrorgId = viewChrorgMapper.selectorgId(pkorg);

                        String olddept = paramObj.getString("old_dept");
                        String deptStr = null;
                        if (ObjectToUtil.isNullOREmpty(olddept)) {
                            //old_dept为空
                            deptStr = paramObj.getString("HR002_ID");
                        } else {
                            //old_dept不为空,查询old_dept是否存在于数据库中
                            Integer olddeptCount = viewChrorgMapper.selectorgdeptcount(olddept);
                            if (olddeptCount == 1) {
                                deptStr = olddept;
                            }else {
                                deptStr = paramObj.getString("HR002_ID");
//                                throw new NDSException("旧组织下不存在或存在多条该部门数据，更新失败！");
                            }
                        }

                        Integer orgDeptCount = viewChrorgMapper.selectorgdeptcount(deptStr);
                        if (orgDeptCount > 0) {
                            //则更新表【组织】表CP_C_HRORG中字段
                            List<HashMap> hrorgidlist = viewChrorgMapper.selectorgdeptId(deptStr);
                            if (hrorgidlist.size() > 1) {
                                throw new NDSException("CP_C_HRORG表HR002_ID条件存在多行记录：" + paramObj.getString("HR002_ID"));
                            }
                            HashMap storeMap = hrorgidlist.get(0);
                            Long hrorgid = (Long) storeMap.get("ID");

                            JSONObject updateObj = new JSONObject();
                            updateObj.put("ECODE", paramObj.getString("ECODE"));
                            updateObj.put("ENAME", paramObj.getString("ENAME"));
                            updateObj.put("HR002_ID", paramObj.getString("HR002_ID"));
                            updateObj.put("CP_C_ORGUP_ID", cphrorgId);
                            updateObj.put("ORGTYPE", "IN");
                            updateObj.put("ISACTIVE", paramObj.getString("ISACTIVE"));
                            updateObj.put("MODIFIEDDATE", paramObj.getString("MODIFIEDDATE"));

//                            updateObj.put("MIXNAME", "[" + paramObj.getString("ECODE") + "]" + paramObj.getString("ENAME"));
                            //TODO 不调标准服务
//                            updateObj.put("MODIFIERNAME", user.getName());
//                            updateObj.put("MODIFIERENAME", user.getEname());
//                            updateObj.put("MODIFIERID", Integer.valueOf(user.getId()).longValue());
//                            updateObj.put("ID", hrorgid);
//                            int updateRes = viewChrorgMapper.updateHrorg(updateObj);
//                            if (updateRes <= 0) {
//                                throw new NDSException("组织修改失败");
//                            }

                            //TODO 调用标准服务
                            JSONObject jo = new JSONObject();
                            jo.put("objid", hrorgid);
                            jo.put("table", "CP_C_INORG");
                            JSONObject fixJo = new JSONObject();
                            fixJo.put("CP_C_INORG", updateObj);
                            jo.put("fixcolumn", fixJo);
                            QuerySessionImpl userquerySession = new QuerySessionImpl(user);
                            DefaultWebEvent event = new DefaultWebEvent("test", new HashMap());
                            event.put("param", jo);
                            userquerySession.setEvent(event);
                            JSONObject retJo = postHandleEvent.executePostHandle(jo, userquerySession, event, "save");
                            if (retJo.get("code") != null && (int) retJo.get("code") < 0) {
                                throw new NDSException("" + retJo.get("message") + retJo.get("error"));
                            }


//                            Object orgO = ReferenceUtil.refer(ApplicationContextHandle.getApplicationContext(), "com.jackrain.nea.cp.api.ChrorgSaveCmd", "cp", "1.0");
//                            ValueHolder result = ((ChrorgSaveCmd) orgO).execute(userquerySession);


                        } else {
                            //判断FC组织表中是否存在ECODE=CODE的数据
                            Integer codeCount = viewChrorgMapper.selectcountcode(paramObj.getString("ECODE"));
                            if (codeCount > 0) {
                                throw new NDSException(paramObj.getString("ECODE") + "部门存在相同编码的组织数据，新增失败！");
                            }
                            //新增组织表

                            JSONObject insertObj = new JSONObject();

                            insertObj.put("HR002_ID", paramObj.getString("HR002_ID"));
                            insertObj.put("ECODE", paramObj.getString("ECODE"));
                            insertObj.put("ENAME", paramObj.getString("ENAME"));
                            insertObj.put("CP_C_ORGUP_ID", cphrorgId);
                            insertObj.put("ORGTYPE", "IN");
                            insertObj.put("ISACTIVE", paramObj.getString("ISACTIVE"));
                            insertObj.put("CREATIONDATE", paramObj.getString("MODIFIEDDATE"));
                            insertObj.put("MODIFIEDDATE", paramObj.getString("MODIFIEDDATE"));

//                            insertObj.put("MIXNAME", "[" + paramObj.getString("ECODE") + "]" + paramObj.getString("ENAME"));
                            //TODO 不调用标准服务
//                            insertObj.put("MODIFIERNAME", user.getName());
//                            insertObj.put("MODIFIERENAME", user.getEname());
//                            insertObj.put("MODIFIERID", Integer.valueOf(user.getId()).longValue());
//                            insertObj.put("OWNERID", Integer.valueOf(user.getId()).longValue());
//                            insertObj.put("OWNERNAME", user.getName());
//                            insertObj.put("OWNERENAME", user.getEname());
//                            insertObj.put("AD_CLIENT_ID", Integer.valueOf(user.getClientId()).longValue());
//                            insertObj.put("AD_ORG_ID", Integer.valueOf(user.getOrgId()).longValue());
//                            Long hrorgid = Tools.getSequence("CP_C_HRORG");
//                            insertObj.put("ID", hrorgid);
//                            int insertRes = viewChrorgMapper.insertHrorg(insertObj);
//                            if (insertRes <= 0) {
//                                throw new NDSException("组织新增失败");
//                            }
                            //TODO 调用标准服务
                            JSONObject jo = new JSONObject();
                            jo.put("objid", -1);
                            jo.put("table", "CP_C_INORG");
                            JSONObject fixJo = new JSONObject();
                            fixJo.put("CP_C_INORG", insertObj);
                            jo.put("fixcolumn", fixJo);
                            QuerySessionImpl userquerySession = new QuerySessionImpl(user);
                            DefaultWebEvent event = new DefaultWebEvent("test", new HashMap());
                            event.put("param", jo);
                            userquerySession.setEvent(event);
                            JSONObject retJo = postHandleEvent.executePostHandle(jo, userquerySession, event, "save");
                            if (retJo.get("code") != null && (int) retJo.get("code") < 0) {
                                throw new NDSException("" + retJo.get("message") + retJo.get("error"));
                            }

//                            Object orgO = ReferenceUtil.refer(ApplicationContextHandle.getApplicationContext(), "com.jackrain.nea.cp.api.ChrorgSaveCmd", "cp", "1.0");
//                            ValueHolder result = ((ChrorgSaveCmd) orgO).execute(userquerySession);

                        }
                    }
                    errIdArray.add(hr002_id);
                }

            } catch (Exception e) {

                JSONObject errrobj = new JSONObject();
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                e.printStackTrace(pw);
                if (e instanceof NDSException) {
                    errrobj.put("message", e.getMessage());
                } else {
                    errrobj.put("message", sw.toString());
                }
                errrobj.put("key", hr002_id);
                errarray.add(errrobj);
            }
        }
        errJo.put("errMessageArr", errarray);
        errJo.put("errIdArr", errIdArray);
        return errJo;
    }

    //处理上级不为空的数据
    public JSONObject handingOrgupIsNotNull(JSONArray paramArray, ViewChrorgMapper viewChrorgMapper, User user) {

        JSONObject errJo = new JSONObject();
        JSONArray errIdArray = new JSONArray();

        JSONArray errarray = new JSONArray();
        //处理pk_fatherorg不为空的数据
        for (int i = 0; i < paramArray.size(); i++) {
            JSONObject paramObj = paramArray.getJSONObject(i);
            String hr002_id = paramObj.getString("HR002_ID");
            try {
                String orgupid = paramObj.getString("pk_fatherorg");
                //上级部门不为空
                if (!ObjectToUtil.isNullOREmpty(orgupid)) {
                    String deptlevel = paramObj.getString("deptlevel");
                    if ("6".equals(deptlevel)) {
                        //门店
                        // 是否存在HR002_ID=【pk_fatherorg】的行
                        String pkorg = paramObj.getString("pk_fatherorg");
                        Integer orgCount = viewChrorgMapper.selectorgdeptcount(pkorg);
                        if (orgCount <= 0) {
                            throw new NDSException(paramObj.getString("ECODE") + "部门的上级部门不存在，数据传输失败！");
                        }
                        List<HashMap> hrorgidlist = viewChrorgMapper.selectorgdeptId(pkorg);
                        if (hrorgidlist.size() > 1) {
                            throw new NDSException("CP_C_HRORG表HR002_ID条件存在多行记录：" + pkorg);
                        }
                        HashMap hrorgMap = hrorgidlist.get(0);
                        Long cphorgId = (Long) hrorgMap.get("ID");
                        //若存在，则取组织的ID，作为门店档案所属组织的ID
                        //判断FC店仓档案表中是否存在HR002_ID=PK_dept字段的数据
                        String olddept = paramObj.getString("old_dept");
                        String deptStr = null;
                        if (ObjectToUtil.isNullOREmpty(olddept)) {
                            //old_dept为空
                            deptStr = paramObj.getString("HR002_ID");
                        } else {
                            //old_dept不为空,查询old_dept是否存在于数据库中
                            Integer olddeptCount = viewChrorgMapper.selectStoreCount(olddept);
                            if (olddeptCount == 1) {
                                deptStr = olddept;
                            } else {
                                deptStr = paramObj.getString("HR002_ID");
//                                throw new NDSException("旧组织下门店档案不存在或存在多条数据，更新失败！");
                            }
                        }
                        Integer orgDeptCount = viewChrorgMapper.selectStoreCount(deptStr);
                        if (orgDeptCount > 0) {
                            //存在更新“编码”、“名称”、“HR组织”、“修改时间”字段的值
                            List<HashMap> storeidlist = viewChrorgMapper.selectStoreId(deptStr);
                            if (storeidlist.size() > 1) {
                                throw new NDSException("CP_C_STORE表HR002_ID条件存在多行记录：" + paramObj.getString("HR002_ID"));
                            }
                            HashMap storeMap = storeidlist.get(0);
                            Long storeid = (Long) storeMap.get("ID");

                            JSONObject updateObj = new JSONObject();
                            updateObj.put("ECODE", paramObj.getString("ECODE"));
                            updateObj.put("CP_C_HRORG_ID", cphorgId);
                            updateObj.put("ENAME", paramObj.getString("ENAME"));
                            updateObj.put("HR002_ID", paramObj.getString("HR002_ID"));

                            if ("N".equals(paramObj.getString("ISACTIVE"))) {
                                updateObj.put("TXTDIM1", "Y");
                            } else if ("Y".equals(paramObj.getString("ISACTIVE"))) {
                                updateObj.put("TXTDIM1", "N");
                            }
                            updateObj.put("MODIFIEDDATE", paramObj.getString("MODIFIEDDATE"));
                            if (!ObjectToUtil.isNullOREmpty(paramObj.getString("HR003_ID"))) {
                                Long bigId = viewChrorgMapper.selectEmpId(paramObj.getString("HR003_ID"));
                                updateObj.put("BIGMANAGER", bigId);
                            }else {

                                updateObj.put("BIGMANAGER", null);

                            }

                            //TODO 不调用标准服务
//                            updateObj.put("MODIFIERNAME", user.getName());
//                            updateObj.put("MODIFIERENAME", user.getEname());
//                            updateObj.put("MODIFIERID", Integer.valueOf(user.getId()).longValue());
//                            updateObj.put("ID", storeid);
//                            int updateRes = viewChrorgMapper.updateStore(updateObj);
//                            if (updateRes <= 0) {
//                                throw new NDSException("部门更新失败");
//                            }
                            //TODO 调标准服务
                            JSONObject jo = new JSONObject();
                            jo.put("objid", storeid);
                            jo.put("table", "CP_C_RSTORE");
                            JSONObject fixJo = new JSONObject();
                            fixJo.put("CP_C_RSTORE", updateObj);
                            jo.put("fixcolumn", fixJo);
                            QuerySessionImpl userquerySession = new QuerySessionImpl(user);
                            DefaultWebEvent event = new DefaultWebEvent("test", new HashMap());
                            event.put("param", jo);
                            userquerySession.setEvent(event);
                            JSONObject retJo = postHandleEvent.executePostHandle(jo, userquerySession, event, "save");
                            if (retJo.get("code") != null && (int) retJo.get("code") < 0) {
                                throw new NDSException("" + retJo.get("message") + retJo.get("error"));
                            }

                        } else {
                            //若不存在则新增一条门店档案的信息
                            JSONObject insertStore = new JSONObject();

                            if ("N".equals(paramObj.getString("ISACTIVE"))) {
                                insertStore.put("TXTDIM1", "Y");
                            } else if ("Y".equals(paramObj.getString("ISACTIVE"))) {
                                insertStore.put("TXTDIM1", "N");
                            }
                            insertStore.put("ECODE", paramObj.getString("ECODE"));
                            insertStore.put("ENAME", paramObj.getString("ENAME"));
                            insertStore.put("STORENATURE", "STO");
                            insertStore.put("CP_C_HRORG_ID", cphorgId);
                            insertStore.put("HR002_ID", paramObj.getString("HR002_ID"));
                            insertStore.put("MODIFIEDDATE", paramObj.getString("MODIFIEDDATE"));
                            insertStore.put("CREATIONDATE", paramObj.getString("MODIFIEDDATE"));
                            if (!ObjectToUtil.isNullOREmpty(paramObj.getString("HR003_ID"))) {
                                Long bigId = viewChrorgMapper.selectEmpId(paramObj.getString("HR003_ID"));
                                insertStore.put("BIGMANAGER", bigId);
                            }else {

                                insertStore.put("BIGMANAGER", null);

                            }
                            //TODO 不调用标准服务
//                            insertStore.put("AD_CLIENT_ID", Integer.valueOf(user.getClientId()).longValue());
//                            insertStore.put("AD_ORG_ID", Integer.valueOf(user.getOrgId()).longValue());
//                            insertStore.put("MODIFIERNAME", user.getName());
//                            insertStore.put("MODIFIERENAME", user.getEname());
//                            insertStore.put("MODIFIERID", Integer.valueOf(user.getId()).longValue());
//                            insertStore.put("OWNERID", Integer.valueOf(user.getId()).longValue());
//                            insertStore.put("OWNERNAME", user.getName());
//                            insertStore.put("OWNERENAME", user.getEname());
//                            Long storeId = Tools.getSequence("CP_C_STORE");
//                            insertStore.put("ID", storeId);
//                            int insertRes = viewChrorgMapper.insertRstore(insertStore);
//                            if (insertRes <= 0) {
//                                throw new NDSException("部门新增失败");
//                            }
                            //TODO 调标准服务
                            JSONObject jo = new JSONObject();
                            jo.put("objid", -1);
                            jo.put("table", "CP_C_RSTORE");

                            JSONObject fixJo = new JSONObject();
                            fixJo.put("CP_C_RSTORE", insertStore);
                            jo.put("fixcolumn", fixJo);
                            QuerySessionImpl userquerySession = new QuerySessionImpl(user);
                            DefaultWebEvent event = new DefaultWebEvent("test", new HashMap());
                            event.put("param", jo);
                            userquerySession.setEvent(event);
                            JSONObject retJo = postHandleEvent.executePostHandle(jo, userquerySession, event, "save");
                            if (retJo.get("code") != null && (int) retJo.get("code") < 0) {
                                throw new NDSException("" + retJo.get("message") + retJo.get("error"));
                            }
                        }

                    } else {
                        //非门店
                        String pkorg = paramObj.getString("pk_fatherorg");
                        if (ObjectToUtil.isNullOREmpty(pkorg)) {
                            throw new NDSException("所属组织不能为空！");
                        }
                        Integer hr002Count = viewChrorgMapper.selectorgdeptcount(pkorg);
                        if (hr002Count <= 0) {
                            throw new NDSException(paramObj.getString("ECODE") + "部门的上级部门不存在，数据传输失败！");
                        }
                        List<HashMap> cphrorgIdList = viewChrorgMapper.selectorgdeptId(pkorg);
                        if (cphrorgIdList.size() > 1) {
                            throw new NDSException("CP_C_HRORG表HR002_ID条件存在多行记录：" + pkorg);
                        }
                        HashMap cphrorgMap = cphrorgIdList.get(0);
                        Long cphrorgId = (Long) cphrorgMap.get("ID");

                        String olddept = paramObj.getString("old_dept");
                        String deptStr = null;
                        if (ObjectToUtil.isNullOREmpty(olddept)) {
                            //old_dept为空
                            deptStr = paramObj.getString("HR002_ID");
                        } else {
                            //old_dept不为空,查询old_dept是否存在于数据库中
                            Integer olddeptCount = viewChrorgMapper.selectorgdeptcount(olddept);
                            if (olddeptCount == 1) {
                                deptStr = olddept;
                            } else {
                                deptStr = paramObj.getString("HR002_ID");
//                                throw new NDSException("旧组织下不存在或存在多条该部门数据，更新失败！");
                            }
                        }
                        Integer orgDeptCount = viewChrorgMapper.selectorgdeptcount(deptStr);

                        if (orgDeptCount > 0) {

                            //则更新表【组织】表CP_C_HRORG中字段
                            List<HashMap> hrorgidlist = viewChrorgMapper.selectorgdeptId(deptStr);
                            if (hrorgidlist.size() > 1) {
                                throw new NDSException("CP_C_HRORG表HR002_ID条件存在多行记录：" + paramObj.getString("HR002_ID"));
                            }
                            HashMap storeMap = hrorgidlist.get(0);
                            Long hrorgid = (Long) storeMap.get("ID");

                            JSONObject updateObj = new JSONObject();
                            updateObj.put("ECODE", paramObj.getString("ECODE"));
                            updateObj.put("ENAME", paramObj.getString("ENAME"));
                            updateObj.put("CP_C_ORGUP_ID", cphrorgId);
                            updateObj.put("ORGTYPE", "IN");
                            updateObj.put("ISACTIVE", paramObj.getString("ISACTIVE"));
                            updateObj.put("MODIFIEDDATE", paramObj.getString("MODIFIEDDATE"));
                            updateObj.put("HR002_ID", paramObj.getString("HR002_ID"));

//                            updateObj.put("MIXNAME", "[" + paramObj.getString("ECODE") + "]" + paramObj.getString("ENAME"));
                            //TODO 不调标准服务
//                            updateObj.put("MODIFIERNAME", user.getName());
//                            updateObj.put("MODIFIERENAME", user.getEname());
//                            updateObj.put("MODIFIERID", Integer.valueOf(user.getId()).longValue());
//                            updateObj.put("ID", hrorgid);
//                            int updateRes = viewChrorgMapper.updateHrorg(updateObj);
//                            if (updateRes <= 0) {
//                                throw new NDSException("组织修改失败");
//                            }

                            //TODO 调用标准服务
                            JSONObject jo = new JSONObject();
                            jo.put("objid", hrorgid);
                            jo.put("table", "CP_C_INORG");
                            JSONObject fixJo = new JSONObject();
                            fixJo.put("CP_C_INORG", updateObj);
                            jo.put("fixcolumn", fixJo);
                            QuerySessionImpl userquerySession = new QuerySessionImpl(user);
                            DefaultWebEvent event = new DefaultWebEvent("test", new HashMap());
                            event.put("param", jo);
                            userquerySession.setEvent(event);
                            JSONObject retJo = postHandleEvent.executePostHandle(jo, userquerySession, event, "save");
                            if (retJo.get("code") != null && (int) retJo.get("code") < 0) {
                                throw new NDSException("" + retJo.get("message") + retJo.get("error"));
                            }

//                            Object orgO = ReferenceUtil.refer(ApplicationContextHandle.getApplicationContext(), "com.jackrain.nea.cp.api.ChrorgSaveCmd", "cp", "1.0");
//                            ValueHolder result = ((ChrorgSaveCmd) orgO).execute(userquerySession);


                        } else {

                            //判断FC组织表中是否存在ECODE=CODE的数据
                            Integer codeCount = viewChrorgMapper.selectcountcode(paramObj.getString("ECODE"));
                            if (codeCount > 0) {
                                throw new NDSException(paramObj.getString("ECODE") + "部门存在相同编码的组织数据，新增失败！");
                            }
                            //新增组织表
                            JSONObject insertObj = new JSONObject();
                            insertObj.put("HR002_ID", paramObj.getString("HR002_ID"));
                            insertObj.put("ECODE", paramObj.getString("ECODE"));
                            insertObj.put("ENAME", paramObj.getString("ENAME"));
                            insertObj.put("CP_C_ORGUP_ID", cphrorgId);
                            insertObj.put("ORGTYPE", "IN");
                            insertObj.put("ISACTIVE", paramObj.getString("ISACTIVE"));
                            insertObj.put("MODIFIEDDATE", paramObj.getString("MODIFIEDDATE"));
                            insertObj.put("CREATIONDATE", paramObj.getString("MODIFIEDDATE"));

//                            insertObj.put("MIXNAME", "[" + paramObj.getString("ECODE") + "]" + paramObj.getString("ENAME"));
                            //TODO 不调用标准服务
//                            insertObj.put("MODIFIERNAME", user.getName());
//                            insertObj.put("MODIFIERENAME", user.getEname());
//                            insertObj.put("MODIFIERID", Integer.valueOf(user.getId()).longValue());
//                            insertObj.put("OWNERID", Integer.valueOf(user.getId()).longValue());
//                            insertObj.put("OWNERNAME", user.getName());
//                            insertObj.put("OWNERENAME", user.getEname());
//                            insertObj.put("AD_CLIENT_ID", Integer.valueOf(user.getClientId()).longValue());
//                            insertObj.put("AD_ORG_ID", Integer.valueOf(user.getOrgId()).longValue());
//
//                            Long hrorgid = Tools.getSequence("CP_C_HRORG");
//                            insertObj.put("ID", hrorgid);
//                            int insertRes = viewChrorgMapper.insertHrorg(insertObj);
//                            if (insertRes <= 0) {
//                                throw new NDSException("组织新增失败");
//                            }
                            //redis锁
//                            RedisReentrantLock hrorglock = new RedisReentrantLock("CP_C_HRORG:" + paramObj.getString("ECODE"));
//                            try {
//                                if (hrorglock.tryLock(500L, TimeUnit.MILLISECONDS)) {
//                                    Integer codeCount = viewChrorgMapper.selectcountcode(paramObj.getString("ECODE"));
//                                    if (codeCount <= 0) {
//                                        Long hrorgid = Tools.getSequence("CP_C_HRORG");
//                                        insertObj.put("ID", hrorgid);
//                                        viewChrorgMapper.insertHrorg(insertObj);
//                                    } else {
//                                        throw new NDSException(paramObj.getString("ECODE") + "部门存在相同编码的组织数据，新增失败！");
//                                    }
//                                } else {
//                                    log.info("Redis锁CP_C_HRORG:" + paramObj.getString("ECODE") + "超时");
//                                }
//
//                            } catch (InterruptedException e) {
//                                e.printStackTrace();
//                            } finally {
//                                log.info(Thread.currentThread().getName() + ":unLock");
//                                hrorglock.unlock();
//                            }

                            //TODO 调用标准服务
                            JSONObject fixJo = new JSONObject();
                            fixJo.put("CP_C_INORG", insertObj);
                            JSONObject jo = new JSONObject();
                            jo.put("objid", -1);
                            jo.put("table", "CP_C_INORG");
                            jo.put("fixcolumn", fixJo);
                            QuerySessionImpl userquerySession = new QuerySessionImpl(user);
                            DefaultWebEvent event = new DefaultWebEvent("test", new HashMap());
                            event.put("param", jo);
                            userquerySession.setEvent(event);
                            JSONObject retJo = postHandleEvent.executePostHandle(jo, userquerySession, event, "save");
                            if (retJo.get("code") != null && (int) retJo.get("code") < 0) {
                                throw new NDSException("" + retJo.get("message") + retJo.get("error"));
                            }

//                            Object orgO = ReferenceUtil.refer(ApplicationContextHandle.getApplicationContext(), "com.jackrain.nea.cp.api.ChrorgSaveCmd", "cp", "1.0");
//                            ValueHolder result = ((ChrorgSaveCmd) orgO).execute(userquerySession);

                        }
                    }
                    errIdArray.add(hr002_id);
                }

            } catch (Exception e) {

                JSONObject errrobj = new JSONObject();
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                e.printStackTrace(pw);
                if (e instanceof NDSException) {
                    errrobj.put("message", e.getMessage());
                } else {
                    errrobj.put("message", sw.toString());
                }
                errrobj.put("key", hr002_id);
                errarray.add(errrobj);
            }
        }

        errJo.put("errMessageArr", errarray);
        errJo.put("errIdArr", errIdArray);
        return errJo;
    }
}